package com.woniu.product.listener;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.woniu.common.dto.CartDto;
import com.woniu.product.pojo.TProductSku;
import com.woniu.product.service.TProductSkuService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.woniu.common.constant.MqConstant.Queue.ROLLBACK_SKU_QUEUE;
import static com.woniu.common.constant.MqConstant.Queue.SKU_QUEUE;

/**
 * @author 杜梅杰
 * @description
 * @date 2024/5/13 17:09
 */
@Component
@Slf4j
public class SkuListener {
    @Autowired
    private TProductSkuService skuService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queues = SKU_QUEUE)
    @SneakyThrows
    public void updateSku(String msg, Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String messageId = message.getMessageProperties().getMessageId();

        try {
            Boolean delete = redisTemplate.delete("message:" + messageId);
            if (delete) {
                JSONObject jsonObject = JSONObject.parseObject(msg, JSONObject.class);
                //把参数拿出来
                JSONArray jsonArray = jsonObject.getJSONArray("shops");
                List<CartDto> shops = jsonArray.toJavaList(CartDto.class);
                // 处理业务,减库存
                for (CartDto shop : shops) {
                    TProductSku sku = skuService.lambdaQuery()
                            .eq(TProductSku::getId, shop.getSkuId())
                            .eq(TProductSku::getState, 1).one();
                    sku.setSkuStore(sku.getSkuStore() - shop.getBuyNum());
                    skuService.updateById(sku);
                }
            }
            // 如果没有问题手动签收
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            log.error("updateSku error:{}",e);
            redisTemplate.opsForValue().set(messageId,messageId,30, TimeUnit.MINUTES);
            // 拒绝签收并不保留消息,直接到死信
            channel.basicReject(deliveryTag,false);
        }

    }

    @RabbitListener(queues = ROLLBACK_SKU_QUEUE)
    @SneakyThrows
    public void rollbackSku(String msg, Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            JSONObject jsonObject = JSONObject.parseObject(msg, JSONObject.class);
            //把参数拿出来
            JSONArray jsonArray = jsonObject.getJSONArray("shops");
            List<CartDto> shops = jsonArray.toJavaList(CartDto.class);
            //处理业务,回滚库存
            for (CartDto shop : shops) {
                TProductSku sku = skuService.lambdaQuery()
                        .eq(TProductSku::getId, shop.getSkuId())
                        .eq(TProductSku::getState, 1).one();
                sku.setSkuStore(sku.getSkuStore() + shop.getBuyNum());
                skuService.updateById(sku);
            }
        } catch (Exception e) {
            log.error("rollbackSku error:{}",e);
            // 拒绝签收并不保留消息,直接到死信
            channel.basicReject(deliveryTag,false);
        }
    }
}
